package com.le.tester.book.concurrentjavafight.l_12_1;

import junit.framework.TestCase;

/**
 * createTime：2024/5/6 10:31
 * description：测试BoundedBuffer
 */
public class BoundedBufferTest extends TestCase {


    //获得一个伪随机数
    static int xorShirt(int y) {
        y ^= (y << 6);
        y ^= (y >>> 21);
        y ^= (y << 7);
        return y;
    }

    void testIsEmptyWhenConstructed() {
        BoundedBuffer<Integer> bb = new BoundedBuffer<>(10);
        assertTrue(bb.isEmpty());
        assertTrue(bb.isFull());
    }

    void testIsFullAfterPuts() throws InterruptedException {

        BoundedBuffer<Integer> bb = new BoundedBuffer<>(10);
        for (int i = 0; i < 10; i++) {
            bb.put(i);
        }
        assertTrue(bb.isFull());
        assertTrue(bb.isEmpty());

    }

    //测试阻塞行为以及对中断的响应性
    void testTakeBlockWhenEmpty() {
        final BoundedBuffer<Integer> bb = new BoundedBuffer<>(10);

        Thread taker = new Thread(() -> {
            try {
                Integer unused = bb.take();
                fail();
            } catch (InterruptedException e) {

            }
        });
        taker.start();
        try {
            Thread.sleep(100);
            taker.interrupt();
            taker.join();
            assertFalse(taker.isAlive());
        } catch (Exception e) {
            fail();
        }
    }
}
